<template>
	<div>
		<!-- v-model="dialogVisible" 用来控制显示隐藏 -->
		<el-dialog v-model="dialogVisible" width="50%" :close-on-click-modal="false" draggable>
			<div style="overflow-y: auto; box-sizing: border-box; height: 500px" v-loading="loading">
				<template v-if="value == '1'">
					<ul class="hr-flex-start" style="flex-wrap: wrap">
						<li v-for="(item, index) in state.list" :key="index" style="margin: 10px 20px; text-align: center; position: relative">
							<a :href="item.path" style="color: white">
								<p style="position: relative; height: 100px; width: 100px">
									<template v-if="isImage(item.path)">
										<el-image style="width: 100px; height: 100px" :src="item.path"></el-image>
									</template>
									<template v-else-if="item.fileType == 'zip'">
										<svg class="icon" aria-hidden="true">
											<use xlink:href="#icon-format-zip"></use>
										</svg>
									</template>
									<template v-else-if="item.fileType == 'txt'">
										<svg class="icon" aria-hidden="true">
											<use xlink:href="#icon-format-txt"></use>
										</svg>
									</template>
									<template v-else-if="item.fileType == 'pdf'">
										<svg class="icon" aria-hidden="true">
											<use xlink:href="#icon-format-pdf"></use>
										</svg>
									</template>
									<template v-else-if="item.fileType == 'doc'">
										<svg class="icon" aria-hidden="true">
											<use xlink:href="#icon-format-doc"></use>
										</svg>
									</template>
									<template v-else-if="item.fileType == 'excel'">
										<svg class="icon" aria-hidden="true">
											<use xlink:href="#icon-format-exl"></use>
										</svg>
									</template>
									<template v-else>
										<svg class="icon" aria-hidden="true">
											<use xlink:href="#icon-goods-inspection"></use>
										</svg>
									</template>
								</p>
								<p class="file-date">{{ item.createdTime }}</p>
								<p class="file-name">
									{{ item.name }}
								</p>
								<p style="position: absolute; top: -18px; right: 10; z-index: 10" v-if="state.canDelete">
									<el-checkbox v-model="item.checked"> </el-checkbox>
								</p>
							</a>
						</li>
					</ul>
				</template>
				<template v-if="value == '2'">
					<div class="w-h-100">
						<el-table :data="state.list" border ref="table" height="100%">
							<el-table-column prop="V_FileName" :label="$t('amspYn9dsfYqwVgmxq2gi')" align="center" width="60" v-if="state.canDelete">
								<template #default="scope">
									<el-checkbox v-model="scope.row.checked"> </el-checkbox>
								</template>
							</el-table-column>
							<el-table-column prop="name" :label="$t('xfiriWqTTr7FAqmuqC0Rz')" align="center"> </el-table-column>
							<el-table-column prop="fileType" :label="$t('0qUxJeOxIsAzpoO4fa7Xo')" align="center"> </el-table-column>
							<el-table-column prop="createdTime" :label="$t('xxAj6fsjvIsQrMdlNpolv')" align="center"> </el-table-column>
							<el-table-column prop="createdUserName" :label="$t('v7AhfaNeGaFoPfZzgpFk')" align="center"> </el-table-column>
							<el-table-column prop="V_CreateAccountName" :label="$t('liBmO8wb58NMw5HLu9Nf')" align="center">
								<template #default="scope">
									<a :href="scope.row.path">
										<el-button type="primary">{{ $t('2KyEk7Ir2Lz3bN9ByjSaE') }}</el-button>
									</a>
								</template>
							</el-table-column>
						</el-table>
					</div>
				</template>
			</div>
			<template #footer v-if="showFooter">
				<div class="dialog-footer">
					<div class="hr-flex-between">
						<div v-if="state.canDelete">
							<el-checkbox v-model="state.selectAll">{{ $t('wH2VzCrbO9LsH30dTs62t') }}</el-checkbox>
						</div>
						<div>
							<slot></slot>
						</div>
						<div>
							<el-button v-if="state.canDelete" type="danger" @click="deleteHandle">{{ $t('c2pZvN1LPTxHnrtcpIde', [getSelectedData.length]) }}</el-button>
							<el-upload
								class="avatar-uploader"
								:auto-upload="false"
								v-model:file-list="state.fileList"
								:show-file-list="false"
								:multiple="true"
								:on-change="(params: any) => uploadChange(params)"
								style="display: inline-block; vertical-align: middle; margin-left: 10px"
							>
								<el-button v-if="state.canAdd" type="primary">{{ $t('sf7FdRax4j7pC9Pcj42uG') }}</el-button>
							</el-upload>
						</div>
					</div>
				</div>
			</template>
			<template #header>
				<div class="hr-flex-between">
					<div class="hr-flex-start">
						<div class="font-20" style="color: white">{{ title }}</div>
						<div style="margin-left: 10px; font-size: 18px; color: white">{{ $t('aD2pL4zX2yLvYi315jZyd', [state.list.length]) }}</div>
					</div>
					<div style="margin-right: 50px; width: 120px">
						<el-select v-model="value" :placeholder="$t('8Wp0QjLURiCjZeAdHog')">
							<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select>
					</div>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import { ref, computed, watch, reactive, toRaw } from 'vue';
import { forEach } from 'lodash';
import { useStaffInfoStore } from '/@/stores/ys/index';
import useCurrentInstance from '/@/utils/hook/useCurrentInstance';
const { proxy } = useCurrentInstance();
const $t = proxy.$t;
const title = $t('s0RrPjQhI7sM2aa8ZYxQ');

const isImage = (filename: any) => {
	// 这是一个数组，包含了我们认为是图片的所有可能的扩展名
	const imageExtensions = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'tiff'];

	// 提取文件扩展名
	const fileExtension = filename.split('.').pop().toLowerCase();

	// 判断文件扩展名是否在我们的图片扩展名数组中
	return imageExtensions.includes(fileExtension);
};

const urlStore = useStaffInfoStore();
// defineProps({
// 	title: {
// 		type: String,
// 		default: $t('s0RrPjQhI7sM2aa8ZYxQ'),
// 	},
// });

const dialogVisible = ref(false);
const loading = ref(false);

type StateType = {
	canDelete: boolean;
	canAdd: boolean;
	list: ListItem[];
	selectAll: boolean;
	uploadMethod?: Function;
	uploadParams?: object;
	uploadFileKey?: string;
	fileList: any[];
	deleteFileMethod?: Function; // 删除文件的接口
	deleteFileKey?: string; // 删除文件用的字段
	deleteFileParams?: object; // 删除文件其他参数
};

type ListItem = {
	id?: string | number; // id
	name?: string; // 文件名字
	path?: string; // 访问路径
	createdTime?: string; // 创建时间
	creater?: string; // 创建人
	checked?: boolean; // 选中标记
	fileType?: string; // 文件类型
};

const state = reactive<StateType>({
	canDelete: false,
	canAdd: false,
	list: [],
	selectAll: false,
	fileList: [],
});

const options = ref([
	{
		value: '1',
		label: $t('tWmRhAaFvHw9ucL22T61U'),
	},
	{
		value: '2',
		label: $t('b9Hmx5OcuEpRJrxpNvVYx'),
	},
]);
const value = ref('1');

let timer: any = null;

const getSelectedData = computed(() => {
	const arr = state.list.filter((item: any) => item.checked === true);
	if (arr.length === state.list.length && arr.length !== 0) {
		checkSelectAll(true);
	} else {
		checkSelectAll(false);
	}
	return arr;
});
//直接在computed修改状态报警告, 使用一个函数
const checkSelectAll = (status: boolean) => {
	state.selectAll = status;
};

const showFooter = computed(() => state.canAdd || state.canDelete);

watch(
	() => state.selectAll,
	(newVal) => {
		if (newVal) {
			state.list.forEach((item: any, index: any) => {
				const item_01 = deepCopy(item);
				item_01.checked = true;
				state.list.splice(index, 1, item_01);
			});
		} else {
			if (state.list.length !== getSelectedData.value.length) return;
			state.list.forEach((item: any, index: any) => {
				const item_01 = deepCopy(item);
				item_01.checked = false;
				state.list.splice(index, 1, item_01);
			});
		}
	}
);

type ParamsType = {
	canDelete?: boolean;
	canAdd?: boolean;
	selectAll?: boolean;
	list: any[];
	uploadMethod?: Function; // 上传文件的接口
	uploadParams?: object; // 上传文件时带上的其他参数
	uploadFileKey?: string; // 上传文件对应的字段，默认 files
	deleteFileMethod?: Function; // 删除文件的接口
	deleteFileKey?: string; // 删除文件用的字段
	deleteFileParams?: object; // 删除文件其他参数
};

const openHandle = (params: ParamsType) => {
	try {
		state.canDelete = params?.canDelete ? true : false;
		state.canAdd = params?.canAdd ? true : false;
		state.selectAll = params?.selectAll ? true : false;
		state.uploadMethod = params?.uploadMethod;
		state.uploadParams = params?.uploadParams;
		state.uploadFileKey = params?.uploadFileKey;
		state.deleteFileKey = params?.deleteFileKey;
		state.deleteFileParams = params?.deleteFileParams;
		state.deleteFileMethod = params?.deleteFileMethod;

		dialogVisible.value = true;
		value.value = '1';

		state.list = deepCopy(setFileType(params.list));
		return new Promise<any>((resolve, reject) => {
			watch(
				() => dialogVisible.value,
				(newVal, oldVal) => {
					if (!newVal) {
						let fileIds = state.list.map((item) => item.id);
						// 返回所有文件的ID
						resolve(fileIds);
					}
				}
			);
		});
	} catch (err) {
		console.log(err);
	}
};

const setFileType = (list: any, typeKey: string = 'name') => {
	list.forEach((item: any) => {
		item.checked = false;
		let fileType = item[typeKey].split('.')[1];
		let imageReg = /jpg|gif|png/; // 图片
		let excelReg = /xlsx|xls/; // Excel 文件
		if (imageReg.test(fileType)) {
			item.fileType = 'image';
		}
		if (excelReg.test(fileType)) {
			item.fileType = 'excel';
		}
		if (fileType == 'pdf') {
			item.fileType = 'pdf';
		}
		if (fileType == 'zip') {
			item.fileType = 'zip';
		}
		if (fileType == 'doc' || fileType == 'docx') {
			item.fileType = 'doc';
		}
		if (fileType == 'txt') {
			item.fileType = 'txt';
		}
	});
	return list;
};
const getFileType = (typeString: any) => {
	let item = '';
	let fileType = typeString.split('.')[1];
	let imageReg = /jpg|gif|png/; // 图片
	let excelReg = /xlsx|xls/; // Excel 文件
	if (imageReg.test(fileType)) {
		item = 'image';
	}
	if (excelReg.test(fileType)) {
		item = 'excel';
	}
	if (fileType == 'pdf') {
		item = 'pdf';
	}
	if (fileType == 'zip') {
		item = 'zip';
	}
	if (fileType == 'doc' || fileType == 'docx') {
		item = 'doc';
	}
	if (fileType == 'txt') {
		item = 'txt';
	}
	return item;
};

function deepCopy(data: any) {
	const res: any = typeof data.splice === 'function' ? [] : {};
	if (typeof data === 'object') {
		for (const key in data) {
			if (data[key] && typeof data[key] === 'object') {
				res[key] = deepCopy(data[key]);
			} else {
				res[key] = data[key];
			}
		}
	}
	return res;
}
const emit = defineEmits(['deleteFile', 'addNewFile']);

//删除接口只支持单文件删除, 删除多文件多次调用接口
const deleteFiles = async (ids: any, key: any) => {
	const promises = ids.map((item: any) => {
		deleteFileAction(item);
	});
	await Promise.all(promises);
};

const deleteFileAction = async (id: any) => {
	if (state?.deleteFileMethod) {
		await state?.deleteFileMethod({
			id: id,
		});
	}

	return new Promise((resolve, reject) => {
		resolve(id);
	});
};

// 删除文件
const deleteHandle = async () => {
 	if (getSelectedData.value.length === 0) return;

	let ids = getSelectedData.value.map((item: any) => item.id);
	//删除操作
	if (state?.deleteFileMethod) {
		try {
			loading.value = true;
			let key = state?.deleteFileKey || 'id';
			await deleteFiles(ids, key);

			emit('deleteFile', ids);

			loading.value = false;
			removeData(state?.list, ids);

			// await state.deleteFileMethod({
			// 	[key]: ids,
			// 	...state?.deleteFileParams,
			// });
		} catch (error) {
			loading.value = false;
		}
	}
};

function removeData(originalArray: any, idArray: any) {
	for (let i = originalArray.length - 1; i >= 0; i--) {
		if (idArray.includes(originalArray[i].id)) {
			originalArray.splice(i, 1);
		}
	}
}

const addNew = () => {
	emit('addNewFile');
};

//上传文件
const uploadChange = (params: any) => {
 	if (timer) {
		clearTimeout(timer);
	}
	timer = setTimeout(async () => {
		let rawArr = state.fileList.map((item) => {
			return item.raw;
		});
		if (state.uploadMethod) {
			try {
				loading.value = true;
				let fileKey = state?.uploadFileKey || 'files';
				let res = await state.uploadMethod({
					[fileKey]: rawArr,
					...state.uploadParams,
				});
				let data = res.data;
				data.forEach((item: any) => {
					let obj = {
						name: params.name,
						fileType: getFileType(params.name),
						path: `${urlStore.url}${item.filePath}`,
						checked: false,
						id: item.n_Id,
						creater: item.createdUserName,
						createdTime: item.createdTime,
					};
					state.list.push(obj);
				});
				loading.value = false;
			} catch (error) {
				loading.value = false;
			}
		}
	}, 100);
};

defineExpose({
	openHandle,
	loading,
});
</script>
<style lang="scss" scoped>
p .icon {
	padding-left: 15px;
	font-size: 110px;
	color: rgb(25, 102, 210);
}
.file-name {
	font-size: 14px;
	font-weight: 500;
	margin-top: 10px;
	width: 120px;
	overflow: hidden;
	color: #666;
}

.file-date {
	font-size: 12px;
	margin: 10px 0;
	color: #999;
}
ul {
	list-style: none;
}
a::selection,
p::selection {
	background: transparent;
	color: inherit;
}
</style>
